﻿using System;
using System.Collections.Specialized;
using System.Linq;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using PD.DataAccess;

namespace PD.Web.DynamicData.FieldTemplates
{
    /// <summary>
    /// Represents the foreign key field template control.
    /// </summary>
    public partial class ForeignKey_EditField : System.Web.DynamicData.FieldTemplateUserControl
    {
        /// <summary>
        /// Gets the data control that handles the data field in a field template.
        /// </summary>
        /// <returns>A data control that handles the data field in a field template.</returns>
        public override Control DataControl
        {
            get
            {
                return this.DropDownList1;
            }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.DropDownList1.Items.Count == 0)
            {
                if (this.Mode == DataBoundControlMode.Insert || !this.Column.IsRequired)
                {
                    this.DropDownList1.Items.Add(new ListItem("[Not Set]", string.Empty));
                }

                this.PopulateListControl(this.DropDownList1);
                this.TryFilterByRole();
            }

            this.SetUpValidator(this.RequiredFieldValidator1);
            this.SetUpValidator(this.DynamicValidator1);
        }

        /// <summary>
        /// Tries to filter by role.
        /// </summary>
        protected void TryFilterByRole()
        {
            FilterByRoleUIHintAttribute filterHint = this.Column.Attributes.OfType<Attribute>().FirstOrDefault(x => x is FilterByRoleUIHintAttribute) as FilterByRoleUIHintAttribute;
            if (filterHint != null && Roles.RoleExists(filterHint.RoleName))
            {
                foreach (ListItem item in this.DropDownList1.Items)
                {
                    if (!string.IsNullOrEmpty(item.Value))
                    {
                        MembershipUser user = Membership.GetUser(new Guid(item.Value));
                        item.Enabled = Roles.IsUserInRole(user.UserName, filterHint.RoleName);
                    }
                }
            }
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.DataBinding"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            string selectedValueString = this.GetSelectedValueString();
            ListItem item = this.DropDownList1.Items.FindByValue(selectedValueString);
            if (item != null)
            {
                this.DropDownList1.SelectedValue = selectedValueString;
            }
        }

        /// <summary>
        /// Provides dictionary access to all data in the current row.
        /// </summary>
        /// <param name="dictionary">The dictionary that contains all the new values.</param>
        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            // If it's an empty string, change it to null
            string value = this.DropDownList1.SelectedValue;
            if (string.IsNullOrEmpty(value))
            {
                value = null;
            }

            this.ExtractForeignKey(dictionary, value);
        }
    }
}
